package http;

/**
 * Created by Crazy on 2018/10/24.
 */

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class LrcFileDownLoad {

    public static final String LLURL = "http://api.bzqll.com/music/tencent/search";


    public static String getSongLRCUrl(String path, String songName)
            throws Exception {
        String url = null;
        int key=579621905;
        int num=100;
        int page=1;
        String str_json = null;

        //歌词名为空返回null
        if(songName == null)
        {
            return null;
        }
        String songname = URLEncoder.encode(songName,"UTF-8");				//编码转换
        String llurl=path+"?key=" + key + "&s=" + songname +"&num="+ num +"&page="+ page;
        str_json = getHtmlCode(llurl);


        JSONObject jsonObject = new JSONObject(str_json);
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        JSONObject item = jsonArray.getJSONObject(0);
        url = item.getString("lrc");
        return url;

    }


    // 获取网页源码
    public static String getHtmlCode(String path) {
        String result = null;
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            InputStream in = connection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String line;
            result = "";
            while ((line = br.readLine()) != null) {
                result += line + "\n";
            }
        }
        catch (Exception e) {
            System.out.println(e.getMessage() + ":" + e.toString());
            return null;
        }
        return result;
    }
}